/* eslint-disable array-callback-return */
import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Table, Button, Modal, Spin, Steps, Badge, Popover, Timeline, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import Link from 'umi/link';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import downloadFile, { getFileName } from '@/utils/utils';

const { Description } = DescriptionList;
const { Step } = Steps;
@connect(({ addempsend, loading, addemprec, reducemprec }) => ({
  addempsend,
  detailsData: reducemprec.detailsData,
  loading: loading.models.addempsend,
  payDetailsData: addemprec.payDetailsData,
}))
@Form.create()
class Problem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      maistrue: false,
      loading: false,
      stepDirection: 'horizontal', //  步骤条方向
      recvOrdCutTaskId: null,
      switchFlag: true,
    };
  }

  componentDidMount() {
    this.getDetail();
  }

  // 详情
  getDetail = () => {
    this.setState({
      loading: true,
    });
    const { dispatch, location } = this.props;
    const { recvOrdCutTaskId } = location.query;
    dispatch({
      type: 'reducemprec/feactorderDetail',
      payload: { recvOrdCutTaskId },
      callback: () => {
        this.setState({
          loading: false,
        });
      },
    });
    this.setState({ recvOrdCutTaskId });
  };

  // 关闭缴纳明细弹框
  handleOk = () => {
    this.setState({
      maistrue: false,
    });
  };

  // 材料信息（来自员工系统）
  getVal = value => {
    if (value.inpVal) {
      if (value.inpType && value.inpType === 9 && value.inpVal !== '[]') {
        return this.addLink(value.inpVal);
      }
      if (value.inpType && value.inpType === 9 && value.inpVal === '[]') {
        return '--';
      }
      return this.commanName(value);
    }
    return '--';
  };

  commanName = item => (item.inpVal ? item.inpVal : '--');

  addLink = matinfo =>
    matinfo.split(',').map(item => {
      const matinfoItem = item.split('|')[1];
      const matinfoName = getFileName(matinfoItem);
      return (
        <span key={item}>
          <a onClick={() => this.downLoad(item)}>{matinfoName}</a>
        </span>
      );
    });

  downLoad = item => {
    const file = item.split('|');
    downloadFile({ fileId: file[0], fileName: getFileName(file[1]) });
  };

  // 减少险种产品的取消回单
  cancelReceipt = record => {
    const { dispatch } = this.props;
    const { recvOrdCutTaskId } = this.state;
    const receArr = [];
    receArr.push(recvOrdCutTaskId);
    dispatch({
      type: 'reducemprec/cancelReturnReceipt',
      payload: record.ass
        ? { ass: record.ass, recvOrdCutTaskId: receArr }
        : { pdId: record.pdId, recvOrdCutTaskId: receArr },
      callback: response => {
        if (response.success) {
          message.success('取消回单成功！');
          dispatch({
            type: 'reducemprec/feactorderDetail',
            payload: {
              recvOrdCutTaskId,
            },
            callback: () => {
              this.setState({
                loading: false,
                switchFlag: true,
              });
            },
          });
        } else {
          message.warning(response.message || '服务器端错误');
        }
      },
    });
  };

  // 分项设置
  subsett = () => {
    const {
      detailsData: { pdInfoDtos, serSetInfoDto },
    } = this.props;
    const { switchFlag } = this.state;
    if (switchFlag === true) {
      let i = 0;
      pdInfoDtos.forEach((item, index) => {
        if (item.pdId === 'PDINF_0000000001') {
          i = index;
          serSetInfoDto.detailDto.map(item1 => {
            const temp = item1;
            temp.pdName = temp.assName;
            temp.sendBeginDate = temp.sendBeginDate;
            temp.cityName = temp.cityName;
          });
          pdInfoDtos.splice(i + 1, 0, ...serSetInfoDto.detailDto);
        }
      });
      this.setState({ switchFlag: false });
    } else {
      let i = 0;
      pdInfoDtos.forEach((item, index) => {
        if (item.pdId === 'PDINF_0000000001') {
          i = index;
          pdInfoDtos.splice(i + 1, serSetInfoDto.detailDto.length); // 将五险的数据截取掉
        }
      });
      this.setState({ switchFlag: true });
    }
  };

  render() {
    const { detailsData, payDetailsData } = this.props;
    const { loading, stepDirection, switchFlag, maistrue } = this.state;
    const newProtInfoDto = [];
    if (detailsData && detailsData.protInfoDto) {
      newProtInfoDto.push(detailsData.protInfoDto);
    }
    //  减少产品
    const newordCutPdList = [];
    if (detailsData.pdInfoDtos) {
      detailsData.pdInfoDtos.map(pditem => {
        newordCutPdList.push(pditem);
      });
    }
    // 减少险种
    const addassColumns = [
      {
        title: '产品',
        dataIndex: 'assName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '执行地',
        dataIndex: 'areaName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '业务结束日期',
        dataIndex: 'endDate',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => {
          if (val && val && moment(val).format('YYYY-MM-01')) {
            const start = val && moment(val).format('YYYY-MM-01');
            const end = moment(start)
              .add('month', 1)
              .add('days', -1)
              .format('YYYY-MM-DD');
            return end;
          }
          return null;
        },
      },
      {
        title: '回单时间',
        dataIndex: 'receTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && moment(val).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        title: '操作',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <div>
            <a onClick={() => this.cancelReceipt(text, record)}>取消回单</a>
          </div>
        ),
      },
    ];
    // 减少产品
    const columns = [
      {
        title: '产品',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '执行地',
        dataIndex: 'cityName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '业务结束日期',
        dataIndex: 'endDate',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => {
          if (val && val && moment(val).format('YYYY-MM-01')) {
            const start = val && moment(val).format('YYYY-MM-01');
            const end = moment(start)
              .add('month', 1)
              .add('days', -1)
              .format('YYYY-MM-DD');
            return end;
          }
          return null;
        },
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <div>
            {record.pdId === 'PDINF_0000000001' ? (
              <span>
                {record.receFlag === 1 ? (
                  <span>
                    {switchFlag ? (
                      <a
                        style={{ marginRight: 16 }}
                        onClick={() => this.cancelReceipt(text, record)}
                      >
                        取消回单
                      </a>
                    ) : null}
                  </span>
                ) : (
                  '--'
                )}
                {switchFlag ? (
                  <span>
                    {detailsData.serSetInfoDto &&
                    detailsData.serSetInfoDto.detailDto &&
                    detailsData.serSetInfoDto.detailDto.length === 0 &&
                    record.receFlag === 2 ? null : (
                      <a
                        style={{ marginLeft: 16 }}
                        onClick={() => {
                          this.subsett(record);
                        }}
                      >
                        分项设置
                      </a>
                    )}
                  </span>
                ) : (
                  <a
                    style={{ marginLeft: 16 }}
                    onClick={() => {
                      this.subsett(record);
                    }}
                  >
                    取消分项设置
                  </a>
                )}
              </span>
            ) : (
              <div>
                {record.pdId === 'PDINF_0000000002' ? (
                  <span>
                    {record.receFlag === 1 ? (
                      <a onClick={() => this.cancelReceipt(text, record)}>取消回单</a>
                    ) : (
                      '--'
                    )}
                  </span>
                ) : (
                  <span>
                    {!switchFlag ? (
                      <a onClick={() => this.cancelReceipt(text, record)}>取消回单</a>
                    ) : null}
                  </span>
                )}
              </div>
            )}
          </div>
        ),
      },
    ];
    // 社保公积金明细
    const insAccuColumns = [
      {
        title: '产品名称',
        dataIndex: 'assName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '业务开始日期',
        dataIndex: 'beginDate',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val ? moment(val).format('YYYY-MM-DD') : '--'),
      },
      {
        title: '业务结束日期',
        dataIndex: 'endDate',
        align: 'center',
        sorter: (a, b) => new Date(b.endDate) - new Date(a.endDate),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => {
          if (val && val && moment(val).format('YYYY-MM-01')) {
            const start = val && moment(val).format('YYYY-MM-01');
            const end = moment(start)
              .add('month', 1)
              .add('days', -1)
              .format('YYYY-MM-DD');
            return end;
          }
          return null;
        },
      },
      {
        title: '缴纳金额',
        dataIndex: 'payAmount',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '企业基数',
        dataIndex: 'entpBase',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '企业比例(%)',
        dataIndex: 'entpProp',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '企业附加(元)',
        dataIndex: 'entpAddnAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '企业缴费',
        dataIndex: 'entpPay',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '个人基数',
        dataIndex: 'perBase',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '个人比例(%)',
        dataIndex: 'perProp',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '个人附加(元)',
        dataIndex: 'perAddnAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '个人缴费',
        dataIndex: 'perPay',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: val => val || (val === 0 ? 0 : null),
      },
      {
        title: '执行地区',
        dataIndex: 'cityName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
    ];

    const customDot = (dot, { status }) =>
      status === 'process' ? (
        <Popover placement="topLeft" arrowPointAtCenter>
          {dot}
        </Popover>
      ) : (
        dot
      );

    // 判断是否为空对象
    const isEmptyObj = obj => {
      if (obj) {
        return JSON.stringify(obj) === '{}';
      }
      return false;
    };
    // 是否含有材料信息
    const isShowMat = () => {
      if (detailsData.coltFlag) {
        if (String(detailsData.coltFlag) === '1') {
          return detailsData && detailsData.dataDtos && detailsData.dataDtos.length ? (
            <DescriptionList style={{ marginBottom: '20px' }}>
              {detailsData.dataDtos.map(item => (
                <Description
                  key={item.matName}
                  term={item.matName}
                  style={{ wordBreak: 'break-all' }}
                >
                  {this.getVal(item)}
                </Description>
              ))}
            </DescriptionList>
          ) : (
            '暂无数据'
          );
        }
        return (
          <DescriptionList style={{ marginBottom: '20px' }}>
            <Description term="材料是否完整">不需要材料</Description>
          </DescriptionList>
        );
      }
      return true;
    };

    const status1 = (item, leafDet) => {
      if (item.operLeafType === 4) {
        return leafDet.doneFlag === 3 ? 'success' : 'default';
      }
      return leafDet.doneFlag === 1 ? 'success' : 'default';
    };

    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          {/* 派单信息 */}
          {detailsData.sendOrdDetailDto && (
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>派单信息</span>}
              style={{ border: '0px', marginBottom: 24 }}
            >
              {(!isEmptyObj(detailsData.sendOrdDetailDto) && (
                <DescriptionList>
                  <Description term="签约方">
                    {detailsData.sendOrdDetailDto.custContName || '--'}
                  </Description>
                  <Description term="客户名称">
                    {detailsData.sendOrdDetailDto.custName || '--'}
                  </Description>
                  {detailsData.sendOrdDetailDto && detailsData.sendOrdDetailDto.evaDate && (
                    <Description term="离职日期">
                      {detailsData.sendOrdDetailDto.evaDate
                        ? moment(detailsData.sendOrdDetailDto.evaDate).format('YYYY-MM-DD')
                        : '--'}
                    </Description>
                  )}
                  {detailsData.sendOrdDetailDto && detailsData.sendOrdDetailDto.deduConFlagName && (
                    <Description term="是否离职联系">
                      {detailsData.sendOrdDetailDto.deduConFlagName || '--'}
                    </Description>
                  )}
                  <Description term="社保停做原因">
                    {detailsData.sendOrdDetailDto.evaReasonName || '--'}
                  </Description>
                  {detailsData.sendOrdDetailDto && detailsData.sendOrdDetailDto.unempFlagName && (
                    <Description term="是否办理失业">
                      {detailsData.sendOrdDetailDto.unempFlagName || '--'}
                    </Description>
                  )}
                  <Description term="操作人">
                    {detailsData.sendOrdDetailDto.recvSuppName || '--'}
                  </Description>
                  {detailsData.sendOrdDetailDto && detailsData.sendOrdDetailDto.sendDate && (
                    <Description term="发单时间">
                      {(detailsData.sendOrdDetailDto.sendDate &&
                        moment(detailsData.sendOrdDetailDto.sendDate).format('YYYY-MM-DD HH:mm')) ||
                        '--'}
                    </Description>
                  )}
                </DescriptionList>
              )) ||
                '暂无数据'}
            </Card>
          )}
          {/* 员工信息 */}
          {detailsData.sendOrdDetailDto && (
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>员工信息</span>}
              style={{ border: '0px', marginBottom: 24 }}
            >
              {(!isEmptyObj(detailsData.sendOrdDetailDto) && (
                <DescriptionList>
                  <Description term="姓名">
                    {detailsData.sendOrdDetailDto.empName || '--'}
                  </Description>
                  <Description term="证件类型">
                    {detailsData.sendOrdDetailDto.idTypeName || '--'}
                  </Description>
                  <Description term="证件号">
                    {detailsData.sendOrdDetailDto.idCode || '--'}
                  </Description>
                  <Description term="国籍">
                    {detailsData.sendOrdDetailDto.nationName || '--'}
                  </Description>
                  <Description term="出生日期">
                    {detailsData.sendOrdDetailDto
                      ? moment(detailsData.sendOrdDetailDto.birthDate).format('YYYY-MM-DD')
                      : '--'}
                  </Description>
                  <Description term="性别">
                    {detailsData.sendOrdDetailDto.genderName || '--'}
                  </Description>
                  <Description term="电话">
                    {detailsData.sendOrdDetailDto.mobile || '--'}
                  </Description>
                  <Description term="员工邮箱">
                    {detailsData.sendOrdDetailDto.email || '--'}
                  </Description>
                </DescriptionList>
              )) ||
                '暂无数据'}
            </Card>
          )}
          {/* 减少产品 */}
          {detailsData.pdInfoDtos && (
            <Card
              style={{ border: '0px', marginBottom: 24 }}
              title={<span style={{ fontWeight: 'bolder' }}>减少产品</span>}
            >
              {(detailsData.pdInfoDtos.length && (
                <Table
                  columns={columns}
                  dataSource={newordCutPdList}
                  pagination={false}
                  style={{ maxWidth: 800 }}
                />
              )) ||
                '暂无数据'}
            </Card>
          )}
          {/* 减少险种 */}
          {detailsData.assDetailDtoList && (
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>减少险种</span>}
              style={{ border: 'none', marginBottom: 24 }}
            >
              {(detailsData.assDetailDtoList.length && (
                <Table
                  dataSource={detailsData.assDetailDtoList || []}
                  columns={addassColumns}
                  rowKey={(_, index) => index}
                  pagination={false}
                />
              )) ||
                '暂无数据'}
            </Card>
          )}
          {/* 执行状态 */}
          {detailsData.execStatusDto && (
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>执行状态</span>}
              style={{ border: '0px', marginBottom: 24 }}
            >
              {detailsData.execStatusDto.leafList && detailsData.execStatusDto.leafList.length ? (
                <Steps
                  direction={stepDirection}
                  progressDot={customDot}
                  style={{ width: '60%', margin: '0 auto', marginTop: 20 }}
                >
                  {detailsData.execStatusDto &&
                    detailsData.execStatusDto.leafList.map(item => (
                      <Step
                        key={item.operLeafTypeName}
                        title={item.operLeafTypeName}
                        description={
                          !item.leafDetList.length ? (
                            `无${item.operLeafType === 3 ? '办理' : '申报'}内容`
                          ) : (
                            <div style={{ width: 400, fontSize: 12, textAlign: 'left' }}>
                              {item.leafDetList.map(leafDet => (
                                <div>
                                  <Badge
                                    status={status1(item, leafDet)}
                                    text={
                                      <span style={{ lineHeight: '30px' }}>
                                        {leafDet.leafDetTypeName} :{leafDet.doneFlagName || '--'}
                                        <span
                                          style={{
                                            fontSize: '12px',
                                            color: '#999',
                                            marginLeft: 15,
                                          }}
                                        >
                                          {leafDet.operTime &&
                                            moment(leafDet.operTime).format('YYYY-MM-DD')}
                                        </span>
                                      </span>
                                    }
                                  />
                                  <br />
                                </div>
                              ))}
                            </div>
                          )
                        }
                        status={item.doneFlag === 1 ? 'finish' : 'wait'}
                      />
                    ))}
                </Steps>
              ) : (
                '暂无数据'
              )}
            </Card>
          )}
          {/* 材料信息 */}
          <Card
            title={<span style={{ fontWeight: 'bolder' }}>材料信息</span>}
            style={{ border: 'none', marginBottom: 16 }}
            id="materialinfo"
          >
            {isShowMat()}
          </Card>
          {/* 办理备注 */}
          {detailsData.handDto && (
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>办理备注</span>}
              style={{ border: 'none', marginBottom: 24 }}
            >
              {(detailsData.handDto.length && (
                <Timeline>
                  {detailsData.handDto.map(item => (
                    <Timeline.Item>
                      <p style={{ float: 'left', margin: '0 15px 0 20px' }}>
                        {item.operTime && moment(item.operTime).format('YYYY-MM-DD HH:mm')}
                      </p>
                      <p style={{ float: 'left', margin: '0 20px 0 15px' }}> {item.operName} </p>
                      <p> {item.content} </p>
                    </Timeline.Item>
                  ))}
                </Timeline>
              )) ||
                '暂无数据'}
            </Card>
          )}
          <FooterToolbar style={{ width: '100%' }}>
            <Link to="/receiveordermanage/reduceemployee/index">
              <Button style={{ marginRight: 10 }}>返回</Button>
            </Link>
          </FooterToolbar>
          <Modal
            width="1200px"
            visible={maistrue}
            onCancel={this.handleOk}
            title="社保公积金明细"
            footer={[
              <Button key="submit" type="primary" onClick={this.handleOk}>
                关闭
              </Button>,
            ]}
          >
            <Card>
              <Table
                dataSource={payDetailsData}
                columns={insAccuColumns}
                rowKey={record => record.serSetId}
                pagination={false}
              />
            </Card>
          </Modal>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Problem;
